/**
 * @param {number[]} candidates
 * @param {number} target
 * @return {number[][]}
 */
var combinationSum2 = function (candidates, target) {
  let resArr = []
  const arrEqual = (arr1, arr2) => {
    if (!arr1 || !arr2) {
      return false
    }
    let equal = arr1.every((item, index) => arr2[index] === item)
    return equal
  }
  candidates = candidates.sort((a, b) => a - b)

  const getData = (num, left, arr) => {
    if (candidates[left] === num) {
      if (left > 0) {
        if (candidates[left] === candidates[0]) {
          arr.push(candidates[left])
          resArr.every(item => !arrEqual(item, arr)) && resArr.push(arr)
          return true
        }
        getData(num, left - 1, [...arr])
      }
      arr.push(candidates[left])
      resArr.every(item => !arrEqual(item, arr)) && resArr.push(arr)
      return true
    } else {
      // 如果当前值比目标值小， 继续减
      // 如果剪完之后的目标值比最小值要小，就没有比的必要了
      arr.push(candidates[left])
      let res = false
      if (num - candidates[left] >= 0) {
        if (left > 0) {
          res = getData(num - candidates[left], left - 1, [...arr])
          if (res && candidates[left] === candidates[0]) {
            return
          }
        }
      }
      let val = candidates[left]
      arr.pop()
      if (left > 0) {
        // if (candidates[left - 1] === candidates[left]) {
        //   left--
        // }
        while (candidates[left] === val && left > 0) {
          left--
        }
        // left--
        getData(num, left, [...arr])
      }
      return
    }
  }
  getData(target, candidates.length - 1, [])
  return resArr
}
console.log(combinationSum2([10, 1, 2, 7, 6, 1, 5], 8))
